<?php

namespace app\admin\model;

use think\Model;
use think\model\concern\SoftDelete;

class Goods extends Model
{
    use SoftDelete;
    // 软删除 字段名
    // protected $deleteTime = 'delete_time';
    // 软删除 字段默认值
    // protected $defaultSoftDelete =null;

    // protected $table = 'table_name';
    // protected $pk = 'id';
    public function searchKeywordsAttr($q, $v, $d)
    {
        $q->where('g.name', 'like', "%{$v}%");
    }
    public function searchShowAttr($q, $v, $d)
    {
        $q->where('g.is_show', '=', "{$v}");
    }
    public function searchHotAttr($q, $v, $d)
    {
        $q->where('g.is_hot', '=', "{$v}");
    }
    public function searchDownAttr($q, $v, $d)
    {
        $q->where('g.is_down', '=', "{$v[0]}");
    }
    public function searchCidAttr($q, $v, $d)
    {
        $q->where('g.cid', '=', "{$v}");
    }
    public function searchTimeqAttr($q, $v, $d)
    {
        $q->where('g.addtime', '< TIME', $v);
    }
    public function searchTimehAttr($q, $v, $d)
    {
        $q->where('g.addtime', '> TIME', $v);
    }
    public function searchPrqAttr($q, $v, $d)
    {
        $q->where('g.price_shop', '>', $v);
    }
    public function searchPrhAttr($q, $v, $d)
    {
        $q->where('g.price_shop', '<', $v);
    }
    public function searchDeleteTimeAttr($q, $v, $d)
    {
        $q->where('g.delete_time', 'not null', '');
    }

    public static function getGoodsList($where, $get, $keywords)
    {
        $list = Goods::field('g.*,c.name cname')
            ->withSearch(array_keys($where), $where)
            ->alias('g')
            ->join('category c', 'g.cid=c.id')->paginate([
                'list_rows' => 5,
                'query' => $get,
            ])->each(function ($item, $k) use ($keywords) {
                $str = '<span style="color:red;">' . $keywords . '</span>';
                $item["name"] = str_replace($keywords, $str, $item['name']);
                return $item;
            });
        return $list;
    }
    public static function getGoodRecoveryList($where, $get, $keywords)
    {
        $list = Goods::onlyTrashed()
            ->field('g.*,c.name cname')
            ->withSearch(array_keys($where), $where)
            ->alias('g')
            ->join('category c', 'g.cid=c.id')->paginate([
                'list_rows' => 5,
                'query' => $get,
            ]);
        return $list;
    }
    public static function addGoods($data)
    {
        try {
            $res = Goods::create($data);
            $msg = '添加成功';
        } catch (\Exception $th) {
            $res = false;
            $msg = $th->getMessage();
        }
        return [$res, $msg];
    }
    public static function editGoods($data)
    {
        try {
            $res = Goods::update($data);
            $msg = '修改成功';
        } catch (\Exception $th) {
            $res = false;
            $msg = $th->getMessage();
        }
        return [$res, $msg];
    }
}
